<template>
  <Dialog
    v-model="dialogVisible"
    width="60%"
    maxHeight="60vh"
    title="上传退款凭证"
    :before-close="() => closeDialog(formRef)"
    class="mobile-dialog"
  >
    <el-form
      :model="form"
      ref="formRef"
      :rules="rules as FormRules"
      label-width="120px"
      :class="isMobile ? 'mobile-form' : ''"
    >
      <div class="w-full flex flex-col">
        <!-- 附件（预览，只读） -->
        <el-form-item label="附件" prop="attachfiles" class="w-100%">
          <PreviewComponent
            v-if="form.attachfiles && form.attachfiles.length"
            :file-list="Array.isArray(form.attachfiles) ? form.attachfiles : [form.attachfiles]"
            :inline-wrap="true"
          />
          <span v-else>-</span>
        </el-form-item>

        <!-- 退款地址（禁用） -->
        <el-form-item label="退款地址" prop="payment_address">
          <el-input
            v-model="form.payment_address"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6 }"
            placeholder="暂无退款地址"
            readonly
            disabled
          />
        </el-form-item>

        <el-form-item :label="t('orderReturn.orderUpload')" prop="att_path" class="w-100%">
          <UploadFile
            url="/common/uploadFile"
            ref="UploadFileRef"
            class="w-100%"
            drag
            multiple
            :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'word', 'txt']"
            :params="{ directory: 6 }"
            :limit="9"
            upload-file-button-name="点击上传或拖拽到此处上传"
            buttonWidth="100%"
            list-type="text"
            :button-link="true"
            :show-file-list="true"
            @upload-success-res="handleUploadCallback"
            @handle-remove-file="handleRemoveFile"
            @handle-picture-card-preview="handlePictureCardPreview"
            :before-upload="handleBeforeUpload"
            @upload-error="handleUploadError"
          />
        </el-form-item>
        <el-form-item :label="t('orderReturn.return_price')" prop="return_price">
          <el-input
            v-model="form.return_price"
            clearable
            type="number"
            :placeholder="t('orderReturn.return_price')"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item :label="t('orderReturn.notes')" prop="notes">
          <el-input
            v-model="form.notes"
            type="textarea"
            :autosize="{ minRows: 10, maxRows: 15 }"
            :placeholder="t('orderReturn.notes')"
          />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div :class="isMobile ? 'mobile-button-group horizontal' : ''">
        <el-button class="m-r-4" @click="closeDialog(formRef)"
          >{{ t('system.parameterConfig.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="submit(formRef)"
          :disabled="!form.att_path.length || uploading"
          :loading="uploading"
        >
          {{ uploading ? t('common.uploading') : t('common.ok') }}
        </el-button>
      </div>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from 'element-plus'
import { uploadPaymentApi } from '@/api/order/pay'
import UploadFile from '@/components/UploadFile/index.vue'
import { createImageViewer } from '@/components/ImageViewer'
import { uploadFileApi, getDetailApi } from '@/api/orderReturn'
import PreviewComponent from '@/components/Preview/index.vue'
import { useAppStore } from '@/store/modules/app'

const { push } = useRouter()
const emit = defineEmits(['refresh'])
const { t } = useI18n()
const appStore = useAppStore()

// 移动端检测
const isMobile = computed(() => appStore.getMobile)

const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance>()

// 添加上传状态管理
const uploading = ref<boolean>(false)
let uploadingCount = 0

// 检查是否所有文件上传完成
const checkUploadComplete = () => {
  if (uploadingCount <= 0) {
    uploading.value = false
  }
}

const form = ref<Record<string, any>>({
  order_id: '',
  att_path: [],
  voucher_id: [],
  return_price: '',
  notes: '',
  attachfiles: [],
  payment_address: ''
})

const rowDetail = ref<Record<string, any>>()

const rules = ref<FormRules>({
  return_price: [
    {
      required: true,
      message: t('orderReturn.return_priceMsg'),
      trigger: 'blur'
    }
  ],
  att_path: [
    {
      required: true,
      message: t('orderReturn.voucherIdMsg'),
      trigger: 'blur'
    }
  ]
})

// 上传前处理
const handleBeforeUpload = () => {
  // 增加上传计数器
  uploadingCount++
  // 如果是第一个文件，设置上传状态
  if (uploadingCount === 1) {
    uploading.value = true
  }
  return true
}

// 上传错误处理
const handleUploadError = () => {
  // 单个文件上传失败，减少计数器
  uploadingCount--
  checkUploadComplete()
}

//上传成功以后回调
const handleUploadCallback = (val: any) => {
  if (!val) return

  if (!form.value.att_path) {
    form.value.att_path = []
  }
  if (!form.value.voucher_id) {
    form.value.voucher_id = []
  }

  form.value.att_path.push(val)
  if (val.id) {
    form.value.voucher_id.push(val.id)
  }

  // 单个文件上传成功，减少计数器
  uploadingCount--
  checkUploadComplete()
}

const handleRemoveFile = (val: any) => {
  if (!val || !val.uid) return

  if (form.value.att_path && form.value.att_path.length) {
    form.value.att_path = form.value.att_path.filter(
      (item: Record<string, any>) => item?.uploadFile?.uid !== val.uid
    )
  }
  if (form.value.voucher_id && form.value.voucher_id.length) {
    form.value.voucher_id = form.value.voucher_id.filter(
      (item: Record<string, any>) => item?.uploadFile?.uid !== val.uid
    )
  }
}

const handlePictureCardPreview = (val: any) => {
  if (!val) return
  createImageViewer({
    urlList: [val]
  })
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (!form.value.att_path.length) {
      ElMessage.error('请上传退款凭证')
      return
    }
    if (valid) {
      ElMessageBox.confirm('退款凭证确认之后无法修改，请谨慎操作', t('purchase.logistics.tips'), {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 将voucher_id数组转换为1,2,3格式的字符串
          const voucherIds = form.value.voucher_id.join(',')

          const resp = await uploadFileApi({
            id: Number(form.value.order_id),
            voucher_id: voucherIds,
            amount: Number(form.value.return_price || 0),
            notes: form.value.notes || ''
          })
          if (resp.code === 0) {
            ElMessage.success(t('orderReturn.uploadSucMsg'))
            closeDialog(formEl)
            emit('refresh')
          }
        })
        .catch(() => {})
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    order_id: '',
    att_path: [],
    voucher_id: [],
    return_price: '',
    notes: '',
    attachfiles: [],
    payment_address: ''
  }
  // 重置上传状态
  uploading.value = false
  uploadingCount = 0

  formEl.resetFields()
  dialogVisible.value = false
}

const getBackShow = async (row: Record<string, any>) => {
  form.value.order_id = row.id
  // 设置退款金额默认值为 pay_amount 或 paid_amount
  form.value.return_price = row.pay_amount || row.paid_amount || 0
  rowDetail.value = row

  // 获取退货退款单详情，使用 returnorder_id 作为查询 ID
  try {
    const queryId = row.returnorder_id || row.id
    const resp = await getDetailApi(queryId)
    if (resp.code === 0 && resp.data) {
      // 处理附件数据格式转换
      if (resp.data.attachfiles && Array.isArray(resp.data.attachfiles)) {
        form.value.attachfiles = resp.data.attachfiles.map((file: any, index: number) => ({
          name: file.name || `file_${index}`,
          url: file.url,
          uid: `file_${file.id || Date.now()}_${index}`,
          status: 'done'
        }))
      } else {
        form.value.attachfiles = []
      }

      // 设置退款地址
      form.value.payment_address = resp.data.payment_address || ''
    }
  } catch (error) {
    console.error('获取详情失败:', error)
  }
}

defineExpose({
  dialogVisible,
  getBackShow
})
</script>
<style lang="less" scoped>
/* 移动端样式 - 仅在移动端生效 */
@media (width <= 768px) {
  .mobile-form {
    .el-form-item {
      margin-bottom: 20px;

      .el-form-item__label {
        display: block;
        width: 100%;
        margin-bottom: 8px;
        text-align: left;
      }

      .el-form-item__content {
        width: 100%;
        margin-left: 0;
      }
    }
  }

  .mobile-button-group {
    display: flex;
    flex-direction: column;
    gap: 10px;

    .el-button {
      width: 100%;
      margin: 0;
    }

    &.horizontal {
      flex-flow: row wrap;

      .el-button {
        flex: 1;
        min-width: 0;
        margin-right: 8px;

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
}

/* 桌面端保持原有样式 */
@media (width >= 769px) {
  .mobile-form {
    .el-form-item {
      margin-bottom: inherit;

      .el-form-item__label {
        display: inherit;
        width: inherit;
        margin-bottom: inherit;
        text-align: inherit;
      }

      .el-form-item__content {
        width: inherit;
        margin-left: inherit;
      }
    }
  }

  .mobile-button-group {
    display: none;
  }
}

/* 附件预览样式 */
.attachfiles-preview {
  .file-item {
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.no-attachments {
  font-style: italic;
  color: #999;
}
</style>
